<template>
  <el-dialog
    v-model="visible"
    title="上传文档"
    width="600px"
    :before-close="handleClose"
  >
    <el-upload
      ref="uploadRef"
      class="upload-demo"
      drag
      multiple
      :auto-upload="false"
      :limit="10"
      :on-exceed="handleExceed"
      :on-change="handleChange"
      :file-list="fileList"
      :show-file-list="true"
      :before-upload="beforeUpload"
    >
      <el-icon class="el-icon--upload"><upload /></el-icon>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          支持上传 PDF、Word、Excel、PPT、图片、文本等格式文件，单文件不超过50MB
        </div>
      </template>
    </el-upload>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="submitUpload" :loading="uploading">
        上传
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadDocuments } from '@/api/document'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const uploadRef = ref(null)
const fileList = ref([])
const uploading = ref(false)

// 监听modelValue变化
watch(() => props.modelValue, (val) => {
  visible.value = val
})

// 监听visible变化
watch(visible, (val) => {
  if (!val) {
    fileList.value = []
  }
  emit('update:modelValue', val)
})

// 关闭对话框
const handleClose = () => {
  visible.value = false
}

// 文件超出限制
const handleExceed = () => {
  ElMessage.warning('一次最多上传10个文件')
}

// 文件变化
const handleChange = (file, files) => {
  fileList.value = files
}

// 上传前校验
const beforeUpload = (file) => {
  const allowedTypes = [
    'application/pdf',
    'application/msword',
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-powerpoint',
    'application/vnd.openxmlformats-officedocument.presentationml.presentation',
    'image/png',
    'image/jpeg',
    'text/plain',
    'text/markdown'
  ]

  const maxSize = 50 * 1024 * 1024 // 50MB

  if (!allowedTypes.includes(file.type)) {
    ElMessage.error(`${file.name} 格式不支持`)
    return false
  }

  if (file.size > maxSize) {
    ElMessage.error(`${file.name} 大小超过50MB限制`)
    return false
  }

  return true
}

// 提交上传
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true

  try {
    const formData = new FormData()
    fileList.value.forEach(file => {
      formData.append('files', file.raw)
    })

    await uploadDocuments(formData)
    ElMessage.success('上传成功')
    emit('success')
    handleClose()
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}
</script>

<style scoped>
.upload-demo {
  text-align: center;
}
</style>